{% extends 'web/base.html' %}
{% load staticfiles %}
{% load my_filters %}
{% block title %}
    企小宝-微团购-编辑
{% endblock %}
{% block content %}
    <style>
        .plus_btn {
            line-height: 30px;
            font-size: 28px;
            color: orangered;
        }

        .minus_btn {
            line-height: 30px;
            font-size: 30px;
            color: #007DDB;
        }
    </style>
    <div class="layui-fluid">
        <div class="layui-row">
            <form class="layui-form" id="groupshopping">
                <input type="hidden" value="{{ groupshopping.id }}" name="id">
                {% csrf_token %}
                <div class="layui-form-item">
                    <label for="title" class="layui-form-label">
                        <span class="x-red">*</span>标题</label>
                    <div class="layui-input-inline col-md-6">
                        <input id="title" name="title" value="{{ groupshopping.title }}" class="layui-input"></div>
                </div>
                <div class="layui-form-item">
                    <label for="title" class="layui-form-label">
                        <span class="x-red">*</span>活动图片</label>
                    <div class="layui-input-inline">
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="image_btn">上传图片</button>
                            <div class="layui-upload-list">
                                <img class="layui-upload-img" src="{{ groupshopping.get_image_url }}" id="image_preview"
                                     style="width: 250px;height: 200px;">
                                <input type="hidden" name="image" value="{{ groupshopping.image }}" id="image">
                                <p id="demoText"></p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label for="start_time" class="layui-form-label">
                        <span class="x-red">*</span>开始时间</label>
                    <div class="layui-input-inline">
                        <input type="text" id="start_time" value="{{ groupshopping.start_time|date:"Y-m-d H:i:s" }}"
                               name="start_time" placeholder="开始时间" lay-verify="required"
                               autocomplete="off"
                               class="layui-input"></div>
                    <label for="end_time" class="layui-form-label">
                        <span class="x-red">*</span>结束时间</label>
                    <div class="layui-input-inline">
                        <input type="text" id="end_time" value="{{ groupshopping.end_time|date:"Y-m-d H:i:s" }}"
                               name="end_time" placeholder="结束时间" lay-verify="required"
                               autocomplete="off"
                               class="layui-input"></div>
                </div>
                <div class="shopping_models">
                    <input type="hidden" name="models" class="models_field">
                    <div class="layui-form-item">
                        <span class="x-red">*</span><label for="" class="layui-form-label">团购形式</label>
                    </div>
                    {% for model in groupshopping.get_models %}

                        <div class="layui-form-item shopping_model">
                            <input type="hidden" d-name="id" value="{{ model.id }}">
                            <label for="" class="layui-form-label">团购人数</label>
                            <div class="layui-input-inline">
                                <input type="number" id="number" value="{{ model.number }}" d-name="number"
                                       lay-verify="number"
                                       autocomplete="off" class="layui-input" placeholder="团购人数"></div>
                            <label for="" class="layui-form-label">对应价格</label>
                            <div class="layui-input-inline">
                                <input type="number" id="price" value="{{ model.price|div100|default:0.0 }}"
                                       d-name="price" lay-verify="number"
                                       autocomplete="off" class="layui-input" placeholder="人数对应价格">
                            </div>
                            {% if forloop.first %}
                                <div class="layui-input-inline">
                                    <span class="plus_btn" onclick="add_model()">+</span>
                                </div>
                            {% else %}
                                <div class="layui-input-inline">
                                    <span class="minus_btn"
                                          onclick="$(this).closest('.shopping_model').remove();">-</span>
                                </div>
                            {% endif %}
                        </div>
                    {% endfor %}
                </div>

                <div class="layui-form-item">
                    <label for="price_original" class="layui-form-label">库存</label>
                    <div class="layui-input-inline">
                        <input type="number" id="inventory" name="inventory"
                               autocomplete="off" class="layui-input"
                               placeholder="不填表示不限制" value="{{ groupshopping.inventory }}"></div>
                </div>
                <div class="layui-form-item">
                    <label for="music" class="layui-form-label">
                        背景音乐(选填)</label>
                    <div class="layui-input-inline">
                        <select class="" lay-filter="music" name="music" id="music">
                            <option value="">请选择</option>
                            {% for music in musics %}
                                <option value="{{ music.id }}"
                                        {% if music.id == groupshopping.music_id %}selected{% endif %}>
                                    {{ music.path }}-{{ music.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="layui-row">
                    <label for="desc" class="layui-form-label">
                        <span class="x-red">*</span>活动简介</label>
                    <div class="layui-input-inline ">
                        <textarea id="desc" name="desc" style="display: none;">{{ groupshopping.desc }}</textarea></div>
                </div>
                <br>
                <br>
                <div class="layui-form-item">
                    <label for="L_repass" class="layui-form-label"></label>
                    <button class="layui-btn" lay-filter="add" lay-submit="">保存并预览</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        function add_model() {
            let models_length = $.find('.shopping_model').length
            if (models_length < 5) {
                let shopping_model = `<div class="layui-form-item shopping_model">
                        <div class="">
                            <label for="" class="layui-form-label">团购人数</label>
                            <div class="layui-input-inline">
                                <input type="number" id="number" d-name="number" lay-verify="number"
                                       autocomplete="off" class="layui-input" placeholder="团购人数"></div>
                            <label for="" class="layui-form-label">对应价格</label>
                            <div class="layui-input-inline">
                                <input type="number" id="price" d-name="price" lay-verify="number"
                                       autocomplete="off" class="layui-input" placeholder="人数对应价格">
                            </div>
                        </div>
                        <div class="layui-input-inline">
                            <span class="minus_btn" onclick="$(this).closest('.shopping_model').remove();">-</span>
                        </div>
                    </div>`
                $('.shopping_models').append(shopping_model);
            } else {
                alert('团购形式最多只能添加5种！');
            }
        }

        layui.use(['form', 'layer', 'laydate', 'upload', 'layedit', 'jquery'],
            function () {
                $ = layui.jquery;
                var form = layui.form,
                    layer = layui.layer,
                    laydate = layui.laydate,
                    upload = layui.upload,
                    layedit = layui.layedit;
                ;
                upload.config.data = {
                    'csrfmiddlewaretoken': $.cookie("csrftoken")
                }
                upload.config.url = '{% url "common:upload" %}';
                //执行一个laydate实例
                laydate.render({
                    elem: '#start_time' //指定元素
                    , type: 'datetime'
                });

                //执行一个laydate实例
                laydate.render({
                    elem: '#end_time' //指定元素
                    , type: 'datetime'
                });
                //图片上传
                var uploadInst = upload.render({
                    elem: '#image_btn'
                    , before: function (obj) {
                        //预读本地文件示例，不支持ie8
                        obj.preview(function (index, file, result) {
                            $('#image_preview').attr('src', result); //图片链接（base64）
                        });
                    }
                    , done: function (res) {
                        //如果上传失败
                        console.log(res)
                        if (res.code > 0) {
                            return layer.msg('上传失败');
                        }
                        //上传成功
                        $('#image').val(res.name)
                    }
                    , error: function () {
                        //演示失败状态，并实现重传
                        var demoText = $('#demoText');
                        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                        demoText.find('.demo-reload').on('click', function () {
                            uploadInst.upload();
                        });
                    }
                });
                //富文本编辑器
                layedit.set({
                    uploadImage: {
                        url: '{% url "common:upload" %}' //接口url
                        , type: 'post' //默认post
                        , tdata: {
                            'csrfmiddlewaretoken': $.cookie("csrftoken")
                        }
                    }
                });
                var desc_t = layedit.build('desc', {
                    height: '90%',//设置编辑器高度,
                    tool: ['strong', 'italic', 'underline', 'del', 'addhr',
                        '|',//分割线
                        'fontFomatt', 'colorpicker', 'left', 'center', 'right',
                        '|',
                        'link', 'unlink', 'image', 'anchors', 'face', 'fullScreen'
                    ]
                });
                //监听提交
                form.on('submit(add)',
                    function (data) {
                        $('#desc').val(layedit.getContent(desc_t));
                        var model_eles = $('.shopping_model');
                        let models = []
                        $.each(model_eles, function (i, ele) {
                            let id = $(ele).find("input[d-name='id']").val();
                            let number = $(ele).find("input[d-name='number']").val();
                            let price = $(ele).find("input[d-name='price']").val();
                            if (id != undefined) {
                                models.push({'id': id, 'number': number, 'price': price});
                            } else {
                                models.push({'number': number, 'price': price});
                            }
                        });
                        let post_data = $(data.form).serializeJSON();
                        post_data['models'] = JSON.stringify(models)
                        $.post("{% url 'groupshopping:edit' shop.id %}", post_data, function (res) {
                                console.log(res);
                                if (res['status'] == 0) {
                                    layer.alert(res.detail, {
                                            icon: 6
                                        },
                                        function () {
                                            xadmin.father_reload();
                                        });
                                } else {
                                    alert(res['detail'])
                                }
                            }
                        );
                        return false;
                    });
            });
    </script>
{% endblock %}